﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crosland.Automotriz.Logic.Linq;
using Crosland.Automotriz.Core;
using Crosland.Automotriz.Seguridad.Entity;
using Crosland.Automotriz.Seguridad.DataAccess;
using Crosland.Automotriz.Seguridad.Business;
using System.Configuration;
using Crosland.Automotriz.Logic;


namespace Crosland.Automotriz.Web
{
    public partial class wFrmCategorizacionClientes : BaseForm
    {    
        clsT_Ven_Categoria_Clientes_CabLogic Logic = new clsT_Ven_Categoria_Clientes_CabLogic();
        clsT_Ven_Categoria_Clientes_DetLogic DetLogic = new clsT_Ven_Categoria_Clientes_DetLogic();
        clsT_Mae_Tabla_General_DetLogic TablaDetLogic = new clsT_Mae_Tabla_General_DetLogic();
        clsUsuarioLogic usu = new clsUsuarioLogic();

        protected override void Inicializar()
        {
            
            gvHistorial.DataSource = Logic.Listar();
            gvHistorial.DataBind();
            gvDetalleHistorial.DataBind();
            ObjectDataSource2.DataBind();
            mvGeneral.SetActiveView(vHistorial);
        }

             
        protected void btnConfirmar_Click(object sender, EventArgs e)
        {
            T_SEG_USUARIO usuario = usu.listarUser(Session[DatosSesion.User].ToString())[0];

            txtPorcB.Text = txtPorcA1.Text;
            txtPorcC.Text = txtPorcB1.Text;

            int a, b, c;
            a = Convert.ToInt32(txtPorcA1.Text) - Convert.ToInt32(txtPorcA.Text);
            b = Convert.ToInt32(txtPorcB1.Text) - Convert.ToInt32(txtPorcB.Text);
            c = Convert.ToInt32(txtPorcC1.Text) - Convert.ToInt32(txtPorcC.Text);


            if (Logic.VerificarProceso(Convert.ToInt32(cboAño.SelectedItem.Value), Convert.ToInt32(cboMes.SelectedItem.Value)))
            {

                try
                {
                    if (Logic.CategorizacionCliente(Convert.ToInt32(cboAño.SelectedItem.Value), Convert.ToInt32(cboMes.SelectedItem.Value), a, b, c, Convert.ToInt32(cboMesAcumulado.SelectedItem.Value), usuario.ID_USUARIO) == true)
                    {
                        //Limpiar(); 
                        string script = "ShowMensaje();";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                        EnviarCorreo(usuario.DES_NOMBRE + " " + usuario.DES_APELLIDOS,"S");


                    }
                    else
                    {
                        string scriptError = "ShowError();";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptError, true);

                    }

                }
                catch (Exception)
                {
                    string scriptValidar = "ShowValidacion();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptValidar, true); ;
                }

            }
            else
            {

                string scriptValidar = "ShowValidacion2();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptValidar, true); ;

            }

            

            
        }

        protected void btnNuevo_Click(object sender, EventArgs e)
        {
            tdActualizar.Visible = false;
            gvDetalleHistorial.DataBind();
            ObjectDataSource2.DataBind();
            Limpiar();
            UsuariosCorreo();
            mvGeneral.SetActiveView(vGenerar);
            

        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            tdActualizar.Visible = true;
            tdProcesar.Visible = true;
            gvDetalleHistorial.DataBind();
            ObjectDataSource2.DataBind();
            mvGeneral.SetActiveView(vHistorial);
            
        }

        void Limpiar()
        {
            
            cboAño.Value = DateTime.Today.Year.ToString();
            cboMes.Value = DateTime.Today.Month.ToString();
            txtPorcA.Text="0";
            txtPorcA1.Text = "50";
            txtPorcB.Text = "50";
            txtPorcB1.Text = "80";
            txtPorcC.Text = "80";
            txtPorcC1.Text = "100";
            cboMesAcumulado.Value = 4;
            
        }

        protected void btnHistorial_Click(object sender, EventArgs e)
        {
            //Response.Redirect("Default.aspx?id=4");
        }

        protected void btnAtras_Click(object sender, EventArgs e)
        {
            //mvGeneral.SetActiveView(vGenerar);
            Response.Redirect("/Repuestos/wFrmDefault.aspx?id=3");
        }

        protected void gvHistorial_PageIndexChanged(object sender, EventArgs e)
        {
            gvHistorial.DataSource = Logic.Listar();
            gvHistorial.DataBind();
        }

        protected void gvHistorial_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgs.CommandArgument);

            if (e.CommandArgs.CommandName == "Detalle")
            {
                
                Session["ID_CAT"] = id;
                //CargarDetalle(id);
                mvGeneral.SetActiveView(vDetalleHistorial);
            }
            

        }

        protected void btnHistorialCab_Click(object sender, EventArgs e)
        {
            gvHistorial.DataSource = Logic.Listar();
            gvHistorial.DataBind();
            mvGeneral.SetActiveView(vHistorial);
        }

        protected void CargarDetalle(int idCat) 
        {

            gvDetalleHistorial.DataSource = DetLogic.Listar(idCat);
            gvDetalleHistorial.DataBind();
        
        }

        protected void gvHistorial_PreRender(object sender, EventArgs e)
        {
            gvHistorial.DataSource = Logic.Listar();
            gvHistorial.DataBind();
        }

        protected void btnVerReport_Click(object sender, EventArgs e)
        {

            if (rbOpciones.SelectedIndex > -1)
            {

                if (rbOpciones.SelectedItem.Value.ToString() == "1")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "openReporte1", String.Format("openReporte1()"), true);
                }
                else if (rbOpciones.SelectedItem.Value.ToString() == "2")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "openReporte2", String.Format("openReporte2()"), true);
                }

            }

        }

        protected void btnModificar_Click(object sender, EventArgs e)
        {
            datosModificar();
            tdProcesar.Visible = false;
            UsuariosCorreo();
            gvDetalleHistorial.DataBind();
            ObjectDataSource2.DataBind();
            mvGeneral.SetActiveView(vGenerar);
        }


        protected void datosModificar()
        {
            int id =Convert.ToInt32(gvHistorial.GetRowValues(gvHistorial.FocusedRowIndex, "ID_CAT"));

            Session["ID_CAT"] = id;

            List<T_VEN_CATEGORIA_CLIENTES_CAB> lista = new List<T_VEN_CATEGORIA_CLIENTES_CAB>();

            lista = Logic.BuscarCategoriaCliente(id);

            cboAño.Value= lista[0].ANIO.ToString();
            cboMes.Value = lista[0].MES.ToString();
            cboMesAcumulado.Value = lista[0].MES_ACU.ToString();
            txtPorcA.Text = lista[0].PORC_A_DESDE.TrimEnd();
            txtPorcA1.Text = lista[0].PORC_A_HASTA.TrimEnd();
            txtPorcB.Text = lista[0].PORC_B_DESDE.TrimEnd();
            txtPorcB1.Text = lista[0].PORC_B_HASTA.TrimEnd();
            txtPorcC.Text = lista[0].PORC_C_DESDE.TrimEnd();
            txtPorcC1.Text = lista[0].PORC_C_HASTA.TrimEnd();
        }

        protected void btnConfirmarA_Click(object sender, EventArgs e)
        {
            T_SEG_USUARIO usuario = usu.listarUser((Session["User"].ToString()).ToString())[0];

            txtPorcB.Text = txtPorcA1.Text;
            txtPorcC.Text = txtPorcB1.Text;

            int id_Cab =Convert.ToInt32(Session["ID_CAT"]);
            string usu_act = usuario.ID_USUARIO;
            string cat_a_d = txtPorcA.Text;
            string cat_a_h = txtPorcA1.Text;
            string cat_b_d = txtPorcB.Text;
            string cat_b_h = txtPorcB1.Text;
            string cat_c_d = txtPorcC.Text;
            string cat_c_h = txtPorcC1.Text;
            int mes_acu=Convert.ToInt32(cboMesAcumulado.SelectedItem.Value);
            int anio = Convert.ToInt32(cboAño.SelectedItem.Value);
            int mes = Convert.ToInt32(cboMes.SelectedItem.Value);



            try
            {
                if (Logic.UpdateCategoriaCliente(id_Cab, usu_act, cat_a_d, cat_a_h, cat_b_d, cat_b_h, cat_c_d, cat_c_h, mes_acu, anio, mes) == true)
                {
                    //Limpiar();
                    string script = "ShowMensaje();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
                    EnviarCorreo(usuario.DES_NOMBRE + " " + usuario.DES_APELLIDOS,"U");

                }
                else
                {
                    string scriptError = "ShowError();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptError, true);

                }

            }
            catch (Exception)
            {
                string scriptValidar = "ShowValidacion();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptValidar, true); ;
            }

            
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            Session["ID_RUC"] = gvDetalleHistorial.GetRowValues(gvDetalleHistorial.FocusedRowIndex,"RUC_CLIENTE").ToString();
            mvGeneral.SetActiveView(vDetalleCliente);
        }

        protected void btnSalirCliente_Click(object sender, EventArgs e)
        {
            gvDetalleHistorial.DataBind();
            mvGeneral.SetActiveView(vDetalleHistorial);
        }

        protected void btnReporte_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "openReporte1", String.Format("openReporte1()"), true);
        }

        protected void UsuariosCorreo()
        {
            int idCab = Convert.ToInt32(ConfigurationManager.AppSettings["UsuarioCorreo"]);

            gvUsuarios.DataSource = TablaDetLogic.ListarUsuariosCorreo(idCab);
            gvUsuarios.DataBind();
        

        }

        protected void EnviarCorreo(string usuario,string indicador)
        {

            List<string> correos = new List<string>();

            for (int i = 0; i < gvUsuarios.VisibleRowCount; i++)
            {

                string row = (string)gvUsuarios.GetRowValues(i,"CORREO").ToString();

                correos.Add(row);

            }
            

            string body=string.Empty;
            string remitente=ConfigurationManager.AppSettings["MailFrom"];

            if (indicador == "S")
            {
                body = "Se acaba de realizar el proceso de categorizacion de clientes.";
            }
            else if(indicador=="U")
            {
                body = "Se acaba de actualizar el proceso de categorizacion de clientes.";
            }

            
            string anio=this.cboAño.SelectedItem.Text;
            string mes=this.cboMes.SelectedItem.Text;
            string desdeA = txtPorcA.Text;
            string hastaA = txtPorcA1.Text;
            string desdeB = txtPorcB.Text;
            string hastaB = txtPorcB1.Text;
            string desdeC = txtPorcC.Text;
            string hastaC = txtPorcC1.Text;

            string mensaje = string.Format(HtmlEmail.HtmlNotificacionCategorizacionCliente,body,anio,mes,usuario,desdeA,hastaA,desdeB,hastaB,desdeC,hastaC);

            Crosland.Util.Util.SendEmail(correos,"Categorizacion de Clientes", mensaje, remitente, null);

        }

        
    
    }
}